<!DOCTYPE HTML>
<html lang="en">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="AverageJoe&#39;s Blog">
    <meta name="description" content="this is my secret garden where I sow my inspirations.">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>AverageJoe&#39;s Blog</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>
<meta name="generator" content="Hexo 5.0.0"><link rel="alternate" href="/atom.xml" title="AverageJoe's Blog" type="application/atom+xml">
</head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">AverageJoe&#39;s Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>Index</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>Tags</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>Categories</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>Archives</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>About</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>Contact</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>Friends</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="Search" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">AverageJoe&#39;s Blog</div>
        <div class="logo-desc">
            
            this is my secret garden where I sow my inspirations.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			Index
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			Tags
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			Categories
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			Archives
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			About
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			Contact
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			Friends
		</a>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('请输入访问本文章的密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/0.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title"></h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                          <div class="article-tag">
                            <span class="chip bg-color">No tag</span>
                          </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>Publish Date:&nbsp;&nbsp;
                    2018-08-14
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>Update Date:&nbsp;&nbsp;
                    2018-08-14
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>Word Count:&nbsp;&nbsp;
                    4.3k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>Read Times:&nbsp;&nbsp;
                    20 Min
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>Read Count:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="0-学习目标"><a href="#0-学习目标" class="headerlink" title="0.学习目标"></a>0.学习目标</h1><h1 id="1-搭建购物车服务"><a href="#1-搭建购物车服务" class="headerlink" title="1.搭建购物车服务"></a>1.搭建购物车服务</h1><h2 id="1-1-创建module"><a href="#1-1-创建module" class="headerlink" title="1.1.创建module"></a>1.1.创建module</h2><p><img src="assets/1533738258872.png" alt="1533738258872"></p>
<p><img src="assets/1533738278599.png" alt="1533738278599"></p>
<h2 id="1-2-pom依赖"><a href="#1-2-pom依赖" class="headerlink" title="1.2.pom依赖"></a>1.2.pom依赖</h2><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">project</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://maven.apache.org/POM/4.0.0&quot;</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xsi:schemaLocation</span>=<span class="string">&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">parent</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>leyou<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.leyou.parent<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.0.0-SNAPSHOT<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">parent</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">modelVersion</span>&gt;</span>4.0.0<span class="tag">&lt;/<span class="name">modelVersion</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.leyou.service<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>ly-cart<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.0.0-SNAPSHOT<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-web<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.cloud<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-cloud-starter-netflix-eureka-client<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.cloud<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-cloud-starter-openfeign<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-data-redis<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">project</span>&gt;</span></span><br></pre></td></tr></table></figure>



<h2 id="1-3-配置文件"><a href="#1-3-配置文件" class="headerlink" title="1.3.配置文件"></a>1.3.配置文件</h2><figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">server:</span></span><br><span class="line">  <span class="attr">port:</span> <span class="number">8088</span></span><br><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">application:</span></span><br><span class="line">    <span class="attr">name:</span> <span class="string">cart-service</span></span><br><span class="line">  <span class="attr">redis:</span></span><br><span class="line">    <span class="attr">host:</span> <span class="number">192.168</span><span class="number">.56</span><span class="number">.101</span></span><br><span class="line"><span class="attr">eureka:</span></span><br><span class="line">  <span class="attr">client:</span></span><br><span class="line">    <span class="attr">service-url:</span></span><br><span class="line">      <span class="attr">defaultZone:</span> <span class="string">http://127.0.0.1:10086/eureka</span></span><br><span class="line">    <span class="attr">registry-fetch-interval-seconds:</span> <span class="number">10</span></span><br><span class="line">  <span class="attr">instance:</span></span><br><span class="line">    <span class="attr">prefer-ip-address:</span> <span class="literal">true</span></span><br><span class="line">    <span class="attr">ip-address:</span> <span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span></span><br><span class="line">    <span class="attr">instance-id:</span> <span class="string">$&#123;eureka.instance.ip-address&#125;.$&#123;server.port&#125;</span></span><br><span class="line">    <span class="attr">lease-renewal-interval-in-seconds:</span> <span class="number">5</span></span><br><span class="line">    <span class="attr">lease-expiration-duration-in-seconds:</span> <span class="number">15</span></span><br></pre></td></tr></table></figure>



<h2 id="1-4-启动类"><a href="#1-4-启动类" class="headerlink" title="1.4.启动类"></a>1.4.启动类</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="meta">@EnableDiscoveryClient</span></span><br><span class="line"><span class="meta">@EnableFeignClients</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LeyouCartApplication</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        SpringApplication.run(LeyouCartApplication.class, args);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h1 id="2-购物车功能分析"><a href="#2-购物车功能分析" class="headerlink" title="2.购物车功能分析"></a>2.购物车功能分析</h1><h2 id="2-1-需求"><a href="#2-1-需求" class="headerlink" title="2.1.需求"></a>2.1.需求</h2><p>需求描述：</p>
<ul>
<li>用户可以在登录状态下将商品添加到购物车<ul>
<li>放入数据库</li>
<li>放入redis（采用）</li>
</ul>
</li>
<li>用户可以在未登录状态下将商品添加到购物车<ul>
<li>放入localstorage</li>
</ul>
</li>
<li>用户可以使用购物车一起结算下单</li>
<li>用户可以查询自己的购物车</li>
<li>用户可以在购物车中修改购买商品的数量。</li>
<li>用户可以在购物车中删除商品。</li>
<li>在购物车中展示商品优惠信息</li>
<li>提示购物车商品价格变化</li>
</ul>
<h2 id="2-2-流程图"><a href="#2-2-流程图" class="headerlink" title="2.2.流程图"></a>2.2.流程图</h2><p><img src="assets/1527585343248.png" alt="1527585343248"></p>
<p>这幅图主要描述了两个功能：新增商品到购物车、查询购物车。</p>
<p>新增商品：</p>
<ul>
<li>判断是否登录<ul>
<li>是：则添加商品到后台Redis中</li>
<li>否：则添加商品到本地的Localstorage</li>
</ul>
</li>
</ul>
<p>无论哪种新增，完成后都需要查询购物车列表：</p>
<ul>
<li>判断是否登录<ul>
<li>否：直接查询localstorage中数据并展示</li>
<li>是：已登录，则需要先看本地是否有数据，<ul>
<li>有：需要提交到后台添加到redis，合并数据，而后查询</li>
<li>否：直接去后台查询redis，而后返回</li>
</ul>
</li>
</ul>
</li>
</ul>
<h1 id="3-未登录购物车"><a href="#3-未登录购物车" class="headerlink" title="3.未登录购物车"></a>3.未登录购物车</h1><h2 id="3-1-准备"><a href="#3-1-准备" class="headerlink" title="3.1.准备"></a>3.1.准备</h2><h3 id="3-1-1购物车的数据结构"><a href="#3-1-1购物车的数据结构" class="headerlink" title="3.1.1购物车的数据结构"></a>3.1.1购物车的数据结构</h3><p>首先分析一下未登录购物车的数据结构。</p>
<p>我们看下页面展示需要什么数据：</p>
<p><img src="assets/1527737419294.png" alt="1527737419294"></p>
<p>因此每一个购物车信息，都是一个对象，包含：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    skuId:<span class="number">2131241</span>,</span><br><span class="line">    title:<span class="string">&quot;小米6&quot;</span>,</span><br><span class="line">    image:<span class="string">&quot;&quot;</span>,</span><br><span class="line">    price:<span class="number">190000</span>,</span><br><span class="line">    num:<span class="number">1</span>,</span><br><span class="line">    ownSpec:<span class="string">&quot;&#123;&quot;</span>机身颜色<span class="string">&quot;:&quot;</span>陶瓷黑尊享版<span class="string">&quot;,&quot;</span>内存<span class="string">&quot;:&quot;</span><span class="number">6</span>GB<span class="string">&quot;,&quot;</span>机身存储<span class="string">&quot;:&quot;</span><span class="number">128</span>GB<span class="string">&quot;&#125;&quot;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>另外，购物车中不止一条数据，因此最终会是对象的数组。即：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">[</span><br><span class="line">    &#123;...&#125;,&#123;...&#125;,&#123;...&#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>



<h3 id="3-1-2-web本地存储"><a href="#3-1-2-web本地存储" class="headerlink" title="3.1.2.web本地存储"></a>3.1.2.web本地存储</h3><p>知道了数据结构，下一个问题，就是如何保存购物车数据。前面我们分析过，可以使用Localstorage来实现。Localstorage是web本地存储的一种，那么，什么是web本地存储呢？</p>
<h4 id="什么是web本地存储？"><a href="#什么是web本地存储？" class="headerlink" title="什么是web本地存储？"></a>什么是web本地存储？</h4><p><img src="assets/1527587496457.png" alt="1527587496457"></p>
<p>web本地存储主要有两种方式：</p>
<ul>
<li>LocalStorage：localStorage 方法存储的数据没有时间限制。第二天、第二周或下一年之后，数据依然可用。 </li>
<li>SessionStorage：sessionStorage 方法针对一个 session 进行数据存储。当用户关闭浏览器窗口后，数据会被删除。 </li>
</ul>
<h4 id="LocalStorage的用法"><a href="#LocalStorage的用法" class="headerlink" title="LocalStorage的用法"></a>LocalStorage的用法</h4><p>语法非常简单：</p>
<p><img src="assets/1533739711101.png" alt="1533739711101"></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">localStorage</span>.setItem(<span class="string">&quot;key&quot;</span>,<span class="string">&quot;value&quot;</span>); <span class="comment">// 存储数据</span></span><br><span class="line"><span class="built_in">localStorage</span>.getItem(<span class="string">&quot;key&quot;</span>); <span class="comment">// 获取数据</span></span><br><span class="line"><span class="built_in">localStorage</span>.removeItem(<span class="string">&quot;key&quot;</span>); <span class="comment">// 删除数据</span></span><br></pre></td></tr></table></figure>

<p>注意：<strong>localStorage和SessionStorage都只能保存字符串</strong>。</p>
<p>不过，在我们的common.js中，已经对localStorage进行了简单的封装：</p>
<p><img src="assets/1533739810927.png" alt="1533739810927"></p>
<p>示例：</p>
<p><img src="assets/1533739929733.png" alt="1533739929733"></p>
<h3 id="3-1-3-获取num"><a href="#3-1-3-获取num" class="headerlink" title="3.1.3.获取num"></a>3.1.3.获取num</h3><p>添加购物车需要知道购物的数量，所以我们需要获取数量大小。我们在Vue中定义num，保存数量：</p>
<p><img src="assets/1533740236299.png" alt="1533740236299"></p>
<p>然后将num与页面的input框绑定，同时给<code>+</code>和<code>-</code>的按钮绑定事件：</p>
<p><img src="assets/1533742284781.png" alt="1533742284781"></p>
<p>编写方法：</p>
<p><img src="assets/1533742493645.png" alt="1533742493645"></p>
<h2 id="3-2-添加购物车"><a href="#3-2-添加购物车" class="headerlink" title="3.2.添加购物车"></a>3.2.添加购物车</h2><h3 id="3-2-1-点击事件"><a href="#3-2-1-点击事件" class="headerlink" title="3.2.1.点击事件"></a>3.2.1.点击事件</h3><p>我们看下商品详情页：</p>
<p><img src="assets/1527585864482.png" alt="1527585864482"></p>
<p>现在点击加入购物车会跳转到购物车成功页面。</p>
<p>不过我们不这么做，我们绑定点击事件，然后实现添加购物车功能。</p>
<p><img src="assets/1533745246878.png" alt="1533745246878"></p>
<p>addCart方法中判断用户的登录状态：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">addCart()&#123;</span><br><span class="line">   ly.http.get(<span class="string">&quot;/auth/verify&quot;</span>).then(<span class="function"><span class="params">res</span>=&gt;</span>&#123;</span><br><span class="line">       <span class="comment">// 已登录发送信息到后台，保存到redis中</span></span><br><span class="line">   &#125;).catch(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">       <span class="comment">// 未登录保存在浏览器本地的localStorage中</span></span><br><span class="line">   &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="3-2-2-获取数量，添加购物车"><a href="#3-2-2-获取数量，添加购物车" class="headerlink" title="3.2.2.获取数量，添加购物车"></a>3.2.2.获取数量，添加购物车</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">addCart()&#123;</span><br><span class="line">    ly.verifyUser().then(<span class="function"><span class="params">res</span>=&gt;</span>&#123;</span><br><span class="line">        <span class="comment">// 已登录发送信息到后台，保存到redis中</span></span><br><span class="line"></span><br><span class="line">    &#125;).catch(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">        <span class="comment">// 未登录保存在浏览器本地的localStorage中</span></span><br><span class="line">        <span class="comment">// 1、查询本地购物车</span></span><br><span class="line">        <span class="keyword">let</span> carts = ly.store.get(<span class="string">&quot;carts&quot;</span>) || [];</span><br><span class="line">        <span class="keyword">let</span> cart = carts.find(<span class="function"><span class="params">c</span>=&gt;</span>c.skuId===<span class="built_in">this</span>.sku.id);</span><br><span class="line">        <span class="comment">// 2、判断是否存在</span></span><br><span class="line">        <span class="keyword">if</span> (cart) &#123;</span><br><span class="line">            <span class="comment">// 3、存在更新数量</span></span><br><span class="line">            cart.num += <span class="built_in">this</span>.num;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// 4、不存在，新增</span></span><br><span class="line">            cart = &#123;</span><br><span class="line">                skuId: <span class="built_in">this</span>.sku.id,</span><br><span class="line">                title: <span class="built_in">this</span>.sku.title,</span><br><span class="line">                price: <span class="built_in">this</span>.sku.price,</span><br><span class="line">                image: <span class="built_in">this</span>.sku.images,</span><br><span class="line">                num: <span class="built_in">this</span>.num,</span><br><span class="line">                ownSpec: <span class="built_in">JSON</span>.stringify(<span class="built_in">this</span>.ownSpec)</span><br><span class="line">            &#125;</span><br><span class="line">            carts.push(cart);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 把carts写回localstorage</span></span><br><span class="line">        ly.store.set(<span class="string">&quot;carts&quot;</span>, carts);</span><br><span class="line">        <span class="comment">// 跳转</span></span><br><span class="line">        <span class="built_in">window</span>.location.href = <span class="string">&quot;http://www.leyou.com/cart.html&quot;</span>;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<p><img src="assets/1533785968759.png" alt="1533785968759"></p>
<p>添加完成后，页面会跳转到购物车结算页面：cart.html</p>
<h2 id="3-3-查询购物车"><a href="#3-3-查询购物车" class="headerlink" title="3.3.查询购物车"></a>3.3.查询购物车</h2><h3 id="3-3-1-校验用户登录"><a href="#3-3-1-校验用户登录" class="headerlink" title="3.3.1.校验用户登录"></a>3.3.1.校验用户登录</h3><p>因为会多次校验用户登录状态，因此我们封装一个校验的方法：</p>
<p>在common.js中：</p>
<p><img src="assets/1533788637942.png" alt="1533788637942"></p>
<p>在页面item.html中使用该方法：</p>
<p><img src="assets/1533788722957.png" alt="1533788722957"></p>
<h3 id="3-3-2-查询购物车"><a href="#3-3-2-查询购物车" class="headerlink" title="3.3.2.查询购物车"></a>3.3.2.查询购物车</h3><p>页面加载时，就应该去查询购物车。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> cartVm = <span class="keyword">new</span> Vue(&#123;</span><br><span class="line">    el: <span class="string">&quot;#cartApp&quot;</span>,</span><br><span class="line">    data: &#123;</span><br><span class="line">        ly,</span><br><span class="line">        carts: [],<span class="comment">// 购物车数据</span></span><br><span class="line">    &#125;,</span><br><span class="line">    created() &#123;</span><br><span class="line">        <span class="keyword">this</span>.loadCarts();</span><br><span class="line">    &#125;,</span><br><span class="line">    methods: &#123;</span><br><span class="line">        loadCarts() &#123;</span><br><span class="line">            <span class="comment">// 先判断登录状态</span></span><br><span class="line">            ly.verifyUser().then(() =&gt; &#123;</span><br><span class="line">                    <span class="comment">// 已登录</span></span><br><span class="line"></span><br><span class="line">                &#125;).<span class="keyword">catch</span>(() =&gt; &#123;</span><br><span class="line">                    <span class="comment">// 未登录</span></span><br><span class="line">                    <span class="keyword">this</span>.carts = ly.store.get(<span class="string">&quot;carts&quot;</span>) || [];</span><br><span class="line">                    <span class="keyword">this</span>.selected = <span class="keyword">this</span>.carts;</span><br><span class="line">                &#125;)</span><br><span class="line">           &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    components: &#123;</span><br><span class="line">        shortcut: () =&gt; <span class="keyword">import</span>(<span class="string">&quot;/js/pages/shortcut.js&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>刷新页面，查看控制台Vue实例：</p>
<p><img src="assets/1533806610234.png" alt="1533806610234"></p>
<h3 id="3-5-2-渲染到页面"><a href="#3-5-2-渲染到页面" class="headerlink" title="3.5.2.渲染到页面"></a>3.5.2.渲染到页面</h3><p>接下来，我们在页面中展示carts的数据：</p>
<p><img src="assets/1533806563740.png" alt="1533806563740"></p>
<p>要注意，价格的展示需要进行格式化，这里使用的是我们在common.js中定义的formatPrice方法</p>
<p>效果：</p>
<p><img src="assets/1533806670775.png" alt="1533806670775"></p>
<h2 id="3-6-修改数量"><a href="#3-6-修改数量" class="headerlink" title="3.6.修改数量"></a>3.6.修改数量</h2><p>我们给页面的 <code>+</code> 和 <code>-</code>绑定点击事件，修改num 的值：</p>
<p><img src="assets/1533806715698.png" alt="1533806715698"></p>
<p>两个事件：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">increment(c) &#123;</span><br><span class="line">    c.num++;</span><br><span class="line">    ly.verifyUser().then(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// TODO 已登录，向后台发起请求</span></span><br><span class="line">    &#125;).catch(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 未登录，直接操作本地数据</span></span><br><span class="line">        ly.store.set(<span class="string">&quot;carts&quot;</span>, <span class="built_in">this</span>.carts);</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;,</span><br><span class="line">decrement(c) &#123;</span><br><span class="line">    <span class="keyword">if</span> (c.num &lt;= <span class="number">1</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    c.num--;</span><br><span class="line">    ly.verifyUser().then(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// TODO 已登录，向后台发起请求</span></span><br><span class="line">    &#125;).catch(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 未登录，直接操作本地数据</span></span><br><span class="line">        ly.store.set(<span class="string">&quot;carts&quot;</span>, <span class="built_in">this</span>.carts);</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="3-7-删除商品"><a href="#3-7-删除商品" class="headerlink" title="3.7.删除商品"></a>3.7.删除商品</h2><p>给删除按钮绑定事件：</p>
<p><img src="assets/1533807671462.png" alt="1533807671462"></p>
<p>点击事件中删除商品：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">deleteCart(i)&#123;</span><br><span class="line">    ly.verifyUser().then(<span class="function"><span class="params">res</span>=&gt;</span>&#123;</span><br><span class="line">        <span class="comment">// TODO，已登录购物车</span></span><br><span class="line">    &#125;).catch(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">        <span class="comment">// 未登录购物车</span></span><br><span class="line">        <span class="built_in">this</span>.carts.splice(i, <span class="number">1</span>);</span><br><span class="line">        ly.store.set(<span class="string">&quot;carts&quot;</span>, <span class="built_in">this</span>.carts);</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="3-8-选中商品"><a href="#3-8-选中商品" class="headerlink" title="3.8.选中商品"></a>3.8.选中商品</h2><p>在页面中，每个购物车商品左侧，都有一个复选框，用户可以选择部分商品进行下单，而不一定是全部：</p>
<p><img src="assets/1533808731995.png" alt="1533808731995"></p>
<p>我们定义一个变量，记录所有被选中的商品：</p>
<p><img src="assets/1533816012100.png" alt="1533816012100"></p>
<h3 id="3-8-1-选中一个"><a href="#3-8-1-选中一个" class="headerlink" title="3.8.1.选中一个"></a>3.8.1.选中一个</h3><p>我们给商品前面的复选框与selected绑定，并且指定其值为当前购物车商品：</p>
<p><img src="assets/1533810163988.png" alt="1533810163988"></p>
<h3 id="3-8-2-初始化全选"><a href="#3-8-2-初始化全选" class="headerlink" title="3.8.2.初始化全选"></a>3.8.2.初始化全选</h3><p>我们在加载完成购物车查询后，初始化全选：</p>
<p><img src="assets/1533809253022.png" alt="1533809253022"></p>
<h3 id="3-8-4-总价格"><a href="#3-8-4-总价格" class="headerlink" title="3.8.4.总价格"></a>3.8.4.总价格</h3><p>然后编写一个计算属性，计算出选中商品总价格：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">computed: &#123;</span><br><span class="line">    totalPrice() &#123;</span><br><span class="line">        <span class="keyword">return</span> ly.formatPrice(<span class="built_in">this</span>.selected.reduce(<span class="function">(<span class="params">c1, c2</span>) =&gt;</span> c1 + c2.num * c2.price, <span class="number">0</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在页面中展示总价格：</p>
<p><img src="assets/1533810788247.png" alt="1533810788247"></p>
<p>效果：</p>
<p><img src="assets/1533810760802.png" alt="1533810760802"></p>
<h1 id="4-已登录购物车"><a href="#4-已登录购物车" class="headerlink" title="4.已登录购物车"></a>4.已登录购物车</h1><p>接下来，我们完成已登录购物车。</p>
<p>在刚才的未登录购物车编写时，我们已经预留好了编写代码的位置，逻辑也基本一致。</p>
<h2 id="4-1-添加登录校验"><a href="#4-1-添加登录校验" class="headerlink" title="4.1.添加登录校验"></a>4.1.添加登录校验</h2><p>购物车系统只负责登录状态的购物车处理，因此需要添加登录校验，我们通过JWT鉴权即可实现。</p>
<h3 id="4-1-1-引入JWT相关依赖"><a href="#4-1-1-引入JWT相关依赖" class="headerlink" title="4.1.1.引入JWT相关依赖"></a>4.1.1.引入JWT相关依赖</h3><p>我们引入之前写的鉴权工具：<code>leyou-auth-common</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.leyou.auth<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>leyou-auth-common<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.0.0-SNAPSHOT<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="4-1-2-配置公钥"><a href="#4-1-2-配置公钥" class="headerlink" title="4.1.2.配置公钥"></a>4.1.2.配置公钥</h3><figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">leyou:</span></span><br><span class="line">  <span class="attr">jwt:</span></span><br><span class="line">    <span class="attr">pubKeyPath:</span> <span class="string">D:/heima/rsa/rsa.pub</span> <span class="comment"># 公钥地址</span></span><br><span class="line">    <span class="attr">cookieName:</span> <span class="string">LY_TOKEN</span> <span class="comment"># cookie的名称</span></span><br></pre></td></tr></table></figure>

<h3 id="4-1-3-加载公钥"><a href="#4-1-3-加载公钥" class="headerlink" title="4.1.3.加载公钥"></a>4.1.3.加载公钥</h3><p> <img src="assets/1533811142851.png" alt="1533811142851"></p>
<p>代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@ConfigurationProperties(prefix = &quot;leyou.jwt&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">JwtProperties</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String pubKeyPath;<span class="comment">// 公钥</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> PublicKey publicKey; <span class="comment">// 公钥</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String cookieName;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger logger = LoggerFactory.getLogger(JwtProperties.class);</span><br><span class="line"></span><br><span class="line">    <span class="meta">@PostConstruct</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 获取公钥和私钥</span></span><br><span class="line">            <span class="keyword">this</span>.publicKey = RsaUtils.getPublicKey(pubKeyPath);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            logger.error(<span class="string">&quot;初始化公钥失败！&quot;</span>, e);</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getPubKeyPath</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> pubKeyPath;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setPubKeyPath</span><span class="params">(String pubKeyPath)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.pubKeyPath = pubKeyPath;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> PublicKey <span class="title">getPublicKey</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> publicKey;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setPublicKey</span><span class="params">(PublicKey publicKey)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.publicKey = publicKey;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getCookieName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> cookieName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setCookieName</span><span class="params">(String cookieName)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.cookieName = cookieName;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="4-1-4-编写拦截器"><a href="#4-1-4-编写拦截器" class="headerlink" title="4.1.4.编写拦截器"></a>4.1.4.编写拦截器</h3><p>因为很多接口都需要进行登录，我们直接编写SpringMVC拦截器，进行统一登录校验。同时，我们还要把解析得到的用户信息保存起来，以便后续的接口可以使用。</p>
<p> <img src="assets/1533811351500.png" alt="1533811351500"></p>
<p>代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LoginInterceptor</span> <span class="keyword">extends</span> <span class="title">HandlerInterceptorAdapter</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> JwtProperties jwtProperties;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 定义一个线程域，存放登录用户</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> ThreadLocal&lt;UserInfo&gt; tl = <span class="keyword">new</span> ThreadLocal&lt;&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">LoginInterceptor</span><span class="params">(JwtProperties jwtProperties)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.jwtProperties = jwtProperties;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">preHandle</span><span class="params">(HttpServletRequest request, HttpServletResponse response, Object handler)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">// 查询token</span></span><br><span class="line">        String token = CookieUtils.getCookieValue(request, <span class="string">&quot;LY_TOKEN&quot;</span>);</span><br><span class="line">        <span class="keyword">if</span> (StringUtils.isBlank(token)) &#123;</span><br><span class="line">            <span class="comment">// 未登录,返回401</span></span><br><span class="line">            response.setStatus(HttpStatus.UNAUTHORIZED.value());</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 有token，查询用户信息</span></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 解析成功，证明已经登录</span></span><br><span class="line">            UserInfo user = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());</span><br><span class="line">            <span class="comment">// 放入线程域</span></span><br><span class="line">            tl.set(user);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e)&#123;</span><br><span class="line">            <span class="comment">// 抛出异常，证明未登录,返回401</span></span><br><span class="line">            response.setStatus(HttpStatus.UNAUTHORIZED.value());</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterCompletion</span><span class="params">(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        tl.remove();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> UserInfo <span class="title">getLoginUser</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> tl.get();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意：</p>
<ul>
<li>这里我们使用了<code>ThreadLocal</code>来存储查询到的用户信息，线程内共享，因此请求到达<code>Controller</code>后可以共享User</li>
<li>并且对外提供了静态的方法：<code>getLoginUser()</code>来获取User信息</li>
</ul>
<h3 id="4-1-5-配置过滤器"><a href="#4-1-5-配置过滤器" class="headerlink" title="4.1.5.配置过滤器"></a>4.1.5.配置过滤器</h3><p>配置SpringMVC，使过滤器生效：</p>
<p> <img src="assets/1533811609498.png" alt="1533811609498"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@EnableConfigurationProperties(JwtProperties.class)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MvcConfig</span> <span class="keyword">implements</span> <span class="title">WebMvcConfigurer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> JwtProperties jwtProperties;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> LoginInterceptor <span class="title">loginInterceptor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> LoginInterceptor(jwtProperties);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addInterceptors</span><span class="params">(InterceptorRegistry registry)</span> </span>&#123;</span><br><span class="line">        registry.addInterceptor(loginInterceptor()).addPathPatterns(<span class="string">&quot;/**&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="4-2-后台购物车设计"><a href="#4-2-后台购物车设计" class="headerlink" title="4.2.后台购物车设计"></a>4.2.后台购物车设计</h2><p>当用户登录时，我们需要把购物车数据保存到后台，可以选择保存在数据库。但是购物车是一个读写频率很高的数据。因此我们这里选择读写效率比较高的Redis作为购物车存储。</p>
<p>Redis有5种不同数据结构，这里选择哪一种比较合适呢？</p>
<ul>
<li>首先不同用户应该有独立的购物车，因此购物车应该以用户的作为key来存储，Value是用户的所有购物车信息。这样看来基本的<code>k-v</code>结构就可以了。</li>
<li>但是，我们对购物车中的商品进行增、删、改操作，基本都需要根据商品id进行判断，为了方便后期处理，我们的购物车也应该是<code>k-v</code>结构，key是商品id，value才是这个商品的购物车信息。</li>
</ul>
<p>综上所述，我们的购物车结构是一个双层Map：Map&lt;String,Map&lt;String,String&gt;&gt;</p>
<ul>
<li>第一层Map，Key是用户id</li>
<li>第二层Map，Key是购物车中商品id，值是购物车数据</li>
</ul>
<p>实体类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Cart</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Long userId;<span class="comment">// 用户id</span></span><br><span class="line">    <span class="keyword">private</span> Long skuId;<span class="comment">// 商品id</span></span><br><span class="line">    <span class="keyword">private</span> String title;<span class="comment">// 标题</span></span><br><span class="line">    <span class="keyword">private</span> String image;<span class="comment">// 图片</span></span><br><span class="line">    <span class="keyword">private</span> Long price;<span class="comment">// 加入购物车时的价格</span></span><br><span class="line">    <span class="keyword">private</span> Integer num;<span class="comment">// 购买数量</span></span><br><span class="line">    <span class="keyword">private</span> String ownSpec;<span class="comment">// 商品规格参数</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Long <span class="title">getUserId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> userId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setUserId</span><span class="params">(Long userId)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.userId = userId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Long <span class="title">getSkuId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> skuId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setSkuId</span><span class="params">(Long skuId)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.skuId = skuId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getTitle</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> title;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setTitle</span><span class="params">(String title)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.title = title;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getImage</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> image;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setImage</span><span class="params">(String image)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.image = image;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Long <span class="title">getPrice</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> price;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setPrice</span><span class="params">(Long price)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.price = price;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">getNum</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> num;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setNum</span><span class="params">(Integer num)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.num = num;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getOwnSpec</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> ownSpec;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setOwnSpec</span><span class="params">(String ownSpec)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.ownSpec = ownSpec;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="4-3-添加商品到购物车"><a href="#4-3-添加商品到购物车" class="headerlink" title="4.3.添加商品到购物车"></a>4.3.添加商品到购物车</h2><h3 id="4-3-1-页面发起请求"><a href="#4-3-1-页面发起请求" class="headerlink" title="4.3.1.页面发起请求"></a>4.3.1.页面发起请求</h3><p>已登录情况下，向后台添加购物车：</p>
<p><img src="assets/1533812224110.png" alt="1533812224110"></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ly.http.post(<span class="string">&quot;/cart&quot;</span>, &#123;<span class="attr">skuId</span>: <span class="built_in">this</span>.sku.id, <span class="attr">num</span>: <span class="built_in">this</span>.num&#125;).then(<span class="function"><span class="params">res</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">window</span>.location = <span class="string">&quot;http://www.leyou.com/cart.html&quot;</span>;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>这里发起的是Json请求。那么我们后台也要以json接收。</p>
<h3 id="4-3-2-编写controller"><a href="#4-3-2-编写controller" class="headerlink" title="4.3.2.编写controller"></a>4.3.2.编写controller</h3><p>先分析一下：</p>
<ul>
<li>请求方式：新增，肯定是Post</li>
<li>请求路径：/cart ，这个其实是Zuul路由的路径，我们可以不管</li>
<li>请求参数：Json对象，包含skuId和num属性</li>
<li>返回结果：无</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CartController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> CartService cartService;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 添加购物车</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@PostMapping</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ResponseEntity&lt;Void&gt; <span class="title">addCart</span><span class="params">(<span class="meta">@RequestBody</span> Cart cart)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.cartService.addCart(cart);</span><br><span class="line">        <span class="keyword">return</span> ResponseEntity.ok().build();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在leyou-gateway中添加路由配置：</p>
<p><img src="assets/1533814103369.png" alt="1533814103369"></p>
<h3 id="4-3-3-CartService"><a href="#4-3-3-CartService" class="headerlink" title="4.3.3.CartService"></a>4.3.3.CartService</h3><p>这里我们不访问数据库，而是直接操作Redis。基本思路：</p>
<ul>
<li>先查询之前的购物车数据</li>
<li>判断要添加的商品是否存在<ul>
<li>存在：则直接修改数量后写回Redis</li>
<li>不存在：新建一条数据，然后写入Redis</li>
</ul>
</li>
</ul>
<p>代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CartService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> StringRedisTemplate redisTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> GoodsClient goodsClient;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> String KEY_PREFIX = <span class="string">&quot;ly:cart:uid:&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> Logger logger = LoggerFactory.getLogger(CartService.class);</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addCart</span><span class="params">(Cart cart)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 获取登录用户</span></span><br><span class="line">        UserInfo user = LoginInterceptor.getLoginUser();</span><br><span class="line">        <span class="comment">// Redis的key</span></span><br><span class="line">        String key = KEY_PREFIX + user.getId();</span><br><span class="line">        <span class="comment">// 获取hash操作对象</span></span><br><span class="line">        BoundHashOperations&lt;String, Object, Object&gt; hashOps = <span class="keyword">this</span>.redisTemplate.boundHashOps(key);</span><br><span class="line">        <span class="comment">// 查询是否存在</span></span><br><span class="line">        Long skuId = cart.getSkuId();</span><br><span class="line">        Integer num = cart.getNum();</span><br><span class="line">        Boolean boo = hashOps.hasKey(skuId.toString());</span><br><span class="line">        <span class="keyword">if</span> (boo) &#123;</span><br><span class="line">            <span class="comment">// 存在，获取购物车数据</span></span><br><span class="line">            String json = hashOps.get(skuId.toString()).toString();</span><br><span class="line">            cart = JsonUtils.parse(json, Cart.class);</span><br><span class="line">            <span class="comment">// 修改购物车数量</span></span><br><span class="line">            cart.setNum(cart.getNum() + num);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// 不存在，新增购物车数据</span></span><br><span class="line">            cart.setUserId(user.getId());</span><br><span class="line">            <span class="comment">// 其它商品信息， 需要查询商品服务</span></span><br><span class="line">            Sku sku = <span class="keyword">this</span>.goodsClient.querySkuById(skuId);</span><br><span class="line">            cart.setImage(StringUtils.isBlank(sku.getImages()) ? <span class="string">&quot;&quot;</span> : StringUtils.split(sku.getImages(), <span class="string">&quot;,&quot;</span>)[<span class="number">0</span>]);</span><br><span class="line">            cart.setPrice(sku.getPrice());</span><br><span class="line">            cart.setTitle(sku.getTitle());</span><br><span class="line">            cart.setOwnSpec(sku.getOwnSpec());</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 将购物车数据写入redis</span></span><br><span class="line">        hashOps.put(cart.getSkuId().toString(), JsonUtils.serialize(cart));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>需要引入leyou-item-interface依赖：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.leyou.item<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>leyou-item-interface<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.0.0-SNAPSHOT<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>



<h3 id="4-3-4-GoodClient"><a href="#4-3-4-GoodClient" class="headerlink" title="4.3.4.GoodClient"></a>4.3.4.GoodClient</h3><p>参照搜索工程，添加GoodClient，提供根据id查询sku的接口：</p>
<p> <img src="assets/1533813101222.png" alt="1533813101222"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@FeignClient(&quot;item-service&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">GoodsClient</span> <span class="keyword">extends</span> <span class="title">GoodsApi</span> </span>&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在leyou-item-service中的GoodsController添加方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@GetMapping(&quot;sku/&#123;id&#125;&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> ResponseEntity&lt;Sku&gt; <span class="title">querySkuById</span><span class="params">(<span class="meta">@PathVariable(&quot;id&quot;)</span>Long id)</span></span>&#123;</span><br><span class="line">    Sku sku = <span class="keyword">this</span>.goodsService.querySkuById(id);</span><br><span class="line">    <span class="keyword">if</span> (sku == <span class="keyword">null</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ResponseEntity&lt;&gt;(HttpStatus.NOT_FOUND);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ResponseEntity.ok(sku);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在leyou-item-service中的GoodsService添加方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Sku <span class="title">querySkuById</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.skuMapper.selectByPrimaryKey(id);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="4-3-5-结果"><a href="#4-3-5-结果" class="headerlink" title="4.3.5.结果"></a>4.3.5.结果</h3><p><img src="assets/1533815211788.png" alt="1533815211788"></p>
<h2 id="4-4-查询购物车"><a href="#4-4-查询购物车" class="headerlink" title="4.4.查询购物车"></a>4.4.查询购物车</h2><h3 id="4-4-1-页面发起请求"><a href="#4-4-1-页面发起请求" class="headerlink" title="4.4.1.页面发起请求"></a>4.4.1.页面发起请求</h3><p>购物车页面：cart.html</p>
<p><img src="assets/1533816059966.png" alt="1533816059966"></p>
<h3 id="4-4-2-后台实现"><a href="#4-4-2-后台实现" class="headerlink" title="4.4.2.后台实现"></a>4.4.2.后台实现</h3><blockquote>
<p>Controller</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 查询购物车列表</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@GetMapping</span></span><br><span class="line"><span class="keyword">public</span> ResponseEntity&lt;List&lt;Cart&gt;&gt; queryCartList() &#123;</span><br><span class="line">    List&lt;Cart&gt; carts = <span class="keyword">this</span>.cartService.queryCartList();</span><br><span class="line">    <span class="keyword">if</span> (carts == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> ResponseEntity.status(HttpStatus.NOT_FOUND).body(<span class="keyword">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ResponseEntity.ok(carts);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>Service</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> List&lt;Cart&gt; <span class="title">queryCartList</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 获取登录用户</span></span><br><span class="line">    UserInfo user = LoginInterceptor.getLoginUser();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 判断是否存在购物车</span></span><br><span class="line">    String key = KEY_PREFIX + user.getId();</span><br><span class="line">    <span class="keyword">if</span>(!<span class="keyword">this</span>.redisTemplate.hasKey(key))&#123;</span><br><span class="line">        <span class="comment">// 不存在，直接返回</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    BoundHashOperations&lt;String, Object, Object&gt; hashOps = <span class="keyword">this</span>.redisTemplate.boundHashOps(key);</span><br><span class="line">    List&lt;Object&gt; carts = hashOps.values();</span><br><span class="line">    <span class="comment">// 判断是否有数据</span></span><br><span class="line">    <span class="keyword">if</span>(CollectionUtils.isEmpty(carts))&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 查询购物车数据</span></span><br><span class="line">    <span class="keyword">return</span> carts.stream().map(o -&gt; JsonUtils.parse(o.toString(), Cart.class)).collect(Collectors.toList());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="4-4-3-测试"><a href="#4-4-3-测试" class="headerlink" title="4.4.3.测试"></a>4.4.3.测试</h3><p><img src="assets/1533815725920.png" alt="1533815725920"></p>
<h2 id="4-5-修改商品数量"><a href="#4-5-修改商品数量" class="headerlink" title="4.5.修改商品数量"></a>4.5.修改商品数量</h2><h3 id="4-5-1-页面发起请求"><a href="#4-5-1-页面发起请求" class="headerlink" title="4.5.1.页面发起请求"></a>4.5.1.页面发起请求</h3><p> <img src="assets/1527996642442.png" alt="1527996642442"></p>
<h3 id="4-5-2-后台实现"><a href="#4-5-2-后台实现" class="headerlink" title="4.5.2.后台实现"></a>4.5.2.后台实现</h3><blockquote>
<p>Controller</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@PutMapping</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> ResponseEntity&lt;Void&gt; <span class="title">updateNum</span><span class="params">(<span class="meta">@RequestParam(&quot;skuId&quot;)</span> Long skuId, </span></span></span><br><span class="line"><span class="function"><span class="params">                                      <span class="meta">@RequestParam(&quot;num&quot;)</span> Integer num)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.cartService.updateNum(skuId, num);</span><br><span class="line">    <span class="keyword">return</span> ResponseEntity.ok().build();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>Service</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">updateNum</span><span class="params">(Long skuId, Integer num)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 获取登录用户</span></span><br><span class="line">    UserInfo user = LoginInterceptor.getLoginUser();</span><br><span class="line">    String key = KEY_PREFIX + user.getId();</span><br><span class="line">    BoundHashOperations&lt;String, Object, Object&gt; hashOps = <span class="keyword">this</span>.redisTemplate.boundHashOps(key);</span><br><span class="line">    <span class="comment">// 获取购物车</span></span><br><span class="line">    String json = hashOps.get(skuId.toString()).toString();</span><br><span class="line">    Cart cart = JsonUtils.parse(json, Cart.class);</span><br><span class="line">    cart.setNum(num);</span><br><span class="line">    <span class="comment">// 写入购物车</span></span><br><span class="line">    hashOps.put(skuId.toString(), JsonUtils.serialize(cart));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="4-6-删除购物车商品"><a href="#4-6-删除购物车商品" class="headerlink" title="4.6.删除购物车商品"></a>4.6.删除购物车商品</h2><h3 id="4-6-1-页面发起请求"><a href="#4-6-1-页面发起请求" class="headerlink" title="4.6.1.页面发起请求"></a>4.6.1.页面发起请求</h3><p><img src="assets/1533816356869.png" alt="1533816356869"></p>
<p>注意：后台成功响应后，要把页面的购物车中数据也删除</p>
<h3 id="4-6-2-后台实现"><a href="#4-6-2-后台实现" class="headerlink" title="4.6.2.后台实现"></a>4.6.2.后台实现</h3><blockquote>
<p>Controller</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@DeleteMapping(&quot;&#123;skuId&#125;&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> ResponseEntity&lt;Void&gt; <span class="title">deleteCart</span><span class="params">(<span class="meta">@PathVariable(&quot;skuId&quot;)</span> String skuId)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.cartService.deleteCart(skuId);</span><br><span class="line">    <span class="keyword">return</span> ResponseEntity.ok().build();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<blockquote>
<p>Service</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">deleteCart</span><span class="params">(String skuId)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 获取登录用户</span></span><br><span class="line">    UserInfo user = LoginInterceptor.getLoginUser();</span><br><span class="line">    String key = KEY_PREFIX + user.getId();</span><br><span class="line">    BoundHashOperations&lt;String, Object, Object&gt; hashOps = <span class="keyword">this</span>.redisTemplate.boundHashOps(key);</span><br><span class="line">    hashOps.delete(skuId);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h1 id="5-登录后购物车合并（作业）"><a href="#5-登录后购物车合并（作业）" class="headerlink" title="5.登录后购物车合并（作业）"></a>5.登录后购物车合并（作业）</h1><p>当跳转到购物车页面，查询购物车列表前，需要判断用户登录状态，</p>
<ul>
<li>如果登录：<ul>
<li>首先检查用户的LocalStorage中是否有购物车信息，</li>
<li>如果有，则提交到后台保存，</li>
<li>清空LocalStorage</li>
</ul>
</li>
<li>如果未登录，直接查询即可</li>
</ul>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        Author:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">AverageJoe</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        Link:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://www.averagejoe.top/2018/08/14/leyou/day18-bi-ji/day18-gou-wu-che/">http://www.averagejoe.top/2018/08/14/leyou/day18-bi-ji/day18-gou-wu-che/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        Reprint policy:
                    </i>
                </span>
                <span class="reprint-info">
                    All articles in this blog are used except for special statements
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    reprint polocy. If reproduced, please indicate source
                    <a href="/about" target="_blank">AverageJoe</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>Copied successfully, please follow the reprint policy of this article</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">more</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            <span class="chip bg-color">No tag</span>
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments textarea {
        box-sizing: border-box;
        background: url("/medias/comment_bg.png") 100% 100% no-repeat;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<script>
    new Valine({
        el: '#vcomments',
        appId: 'BhOC9gMKAfPsRTjqr679tX7A-gzGzoHsz',
        appKey: 'xb9C1I9k62m6AJvin0UWGhSr',
        notify: 'false' === 'true',
        verify: 'false' === 'true',
        visitor: 'true' === 'true',
        avatar: 'mm',
        pageSize: '10',
        lang: 'en',
        placeholder: 'just go go'
    });
</script>

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;Previous</div>
            <div class="card">
                <a href="/2018/08/18/leyou/day19-bi-ji/day19-xia-dan/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/0.jpg" class="responsive-img" alt="">
                        
                        <span class="card-title"></span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            0.学习目标
会调用订单系统接口
实现订单结算功能
实现微信支付功能

1.订单系统接口我们不做开发，只讲解
1.1.导入订单服务把课前资料提供的leyou-order复制到D:\heima\code\leyou目录。
然后在工程内导入：

                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2018-08-18
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-user fa-fw"></i>
                            AverageJoe
                            
                        </span>
                    </div>
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                Next&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2018/07/28/leyou/day16-bi-ji/day16-yong-hu-zhu-ce/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/0.jpg" class="responsive-img" alt="">
                        
                        <span class="card-title"></span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            0.学习目标
独立创建用户中心
了解面向接口开发方式
实现数据校验功能
实现短信发送功能
实现注册功能
实现根据用户名和密码查询用户功能

1.创建用户中心用户搜索到自己心仪的商品，接下来就要去购买，但是购买必须先登录。所以接下来我们编写用
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2018-07-28
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-user fa-fw"></i>
                            AverageJoe
                            
                        </span>
                    </div>
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;TOC</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">2019</span>
            <a href="/about" target="_blank">AverageJoe</a>
            |&nbsp;Powered by&nbsp;<a href="#" target="_blank">AverageJoe</a>
            |&nbsp;Theme&nbsp;<a href="#" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">213.1k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">


    <a href="mailto:1533360044@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1533360044" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1533360044" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;Search</span>
            <input type="search" id="searchInput" name="s" placeholder="Please enter a search keyword"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/search.xml", 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    
	

	<div id="weather-v2-plugin-simple"></div>
<script>
WIDGET = {
  CONFIG: {
    "modules": "0124",
    "background": 1,
    "tmpColor": "FFFFFF",
    "tmpSize": 16,
    "cityColor": "FFFFFF",
    "citySize": 16,
    "aqiSize": 16,
    "weatherIconSize": 24,
    "alertIconSize": 18,
    "padding": "10px 10px 10px 10px",
    "shadow": "1",
    "language": "auto",
    "borderRadius": 5,
    "fixed": "false",
    "vertical": "middle",
    "horizontal": "center",
    "key": "XZgo8dbNqo"
  }
}
</script>
<script src="https://apip.weatherdt.com/simple/static/js/weather-simple-common.js?v=2.0"></script>
<script src="/js/cursor.js"></script>
</body>

</html>
